package com.stylefeng.guns.modular.user_buy_device.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.apple.vo.Paging;
import com.stylefeng.guns.modular.apple_id_manage.dao.AppleIdsMapper;
import com.stylefeng.guns.modular.apple_sign_task_manage.dao.SignTasksMapper;
import com.stylefeng.guns.modular.apple_sign_task_manage.model.MerchantInfoDO;
import com.stylefeng.guns.modular.operation_log.model.MOperationLog;
import com.stylefeng.guns.modular.operation_log.service.IMOperationLogService;
import com.stylefeng.guns.modular.user_buy_device.bo.UserBuyDeviceBO;
import com.stylefeng.guns.modular.user_buy_device.model.UserBuyDeviceDO;
import com.stylefeng.guns.modular.user_buy_device.model.UserBuyDeviceInfo;
import com.stylefeng.guns.modular.user_buy_device.dao.UserBuyDeviceInfoMapper;
import com.stylefeng.guns.modular.user_buy_device.service.IUserBuyDeviceInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 用户购买设备数量信息表 服务实现类
 * </p>
 *
 * @author godrui
 * @since 2020-07-20
 */
@Service
public class UserBuyDeviceInfoServiceImpl extends ServiceImpl<UserBuyDeviceInfoMapper, UserBuyDeviceInfo> implements IUserBuyDeviceInfoService {


    @Resource
    private AppleIdsMapper idsMapper;

    @Resource
    private SignTasksMapper signTasksMapper;

    @Resource
    private IMOperationLogService logService;

    @Override
    public Object getBuyDeviceList(Integer page, Integer limit) {
        int start = (page>0?page-1:page) * limit;

        List<UserBuyDeviceDO> userBuyDeviceDOS = this.baseMapper.getBuyDeviceInfo(start,limit);
        Integer totalCount = this.baseMapper.getInfoTotalCount();

        List<MerchantInfoDO> merchantInfoDOList = signTasksMapper.findMerchantUsedCount2();

        List<UserBuyDeviceBO> deviceCountInfo = new ArrayList<>();
        userBuyDeviceDOS.forEach(u->{
            UserBuyDeviceBO buyDeviceBO = new UserBuyDeviceBO();
            BeanUtils.copyProperties(u,buyDeviceBO);

            int size = merchantInfoDOList.size();
            for (int i=0;i<size;i++){
                //判断是否存在签包项
                if (buyDeviceBO.getUserName().equals(merchantInfoDOList.get(i).getMerchantName())){
                    buyDeviceBO.setUsedCount(merchantInfoDOList.get(i).getDeviceCount());
                    buyDeviceBO.setRemainingCount(u.getDeviceCount() - merchantInfoDOList.get(i).getDeviceCount());
                    merchantInfoDOList.remove(i);
                    break;
                }
            }
            deviceCountInfo.add(buyDeviceBO);
        });

        Paging<UserBuyDeviceBO> paging = new Paging<>();
        paging.setItems(deviceCountInfo);
        paging.setTotal(totalCount.longValue());

        return paging;
    }

    @Override
    public UserBuyDeviceDO getOneUserDevice(Integer id) {
        return this.baseMapper.getOneById(id);
    }

    /**
     * 购买设备数
     * @param deviceInfo
     * @return
     */
    @Override
    @Transactional
    public Object buyDevice(UserBuyDeviceInfo deviceInfo) {
        //可购买设备数
        Integer enableBuyCount = getEnableBuyCount();

        if (enableBuyCount < deviceInfo.getDeviceCount()){
            throw new GunsException(BizExceptionEnum.ID_DIS_ENABLE);
        }

        EntityWrapper<UserBuyDeviceInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id",deviceInfo.getUserId());
        UserBuyDeviceInfo _info = deviceInfo.selectOne(wrapper);

        if (_info != null){
            _info.setDeviceCount(_info.getDeviceCount() + deviceInfo.getDeviceCount());
            _info.setUpdateTime(new Date());
            this.updateById(_info);
        }else{
            deviceInfo.setCreateTime(new Date());
            deviceInfo.setUpdateTime(new Date());
            this.insert(deviceInfo);
        }

        MOperationLog log = new MOperationLog();
        log.setCreateTime(new Date());
        log.setMerchantId(deviceInfo.getUserId());
        log.setUserId(ShiroKit.getUser().getId());
        log.setType(1);
        log.setOperationContent(deviceInfo.getDeviceCount()+"");
        logService.insert(log);

        return new SuccessTip();
    }

    /**
     * 查询可购买设备数量
     * @return
     */
    @Override
    public Integer getEnableBuyCount() {
        //系统可用设备数
        Integer enableCount =  idsMapper.findEnableDeviceCount();
        //已使用总的设备数
        Integer usedTotalCount = signTasksMapper.findUsedDeviceCount();
        //总的购买设备数
        Integer buyTotalCount = this.baseMapper.findAllBuyCount();
        //商户总的剩余设备数
        Integer remainingCount = buyTotalCount - usedTotalCount;
        return enableCount > remainingCount?enableCount-remainingCount:0;
    }
}
